package top.choviwu.garbage.sort.util;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.http.HttpStatus;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.helper.HttpConnection;
import org.jsoup.nodes.Document;
import top.choviwu.garbage.sort.entity.bean.MusicVo;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.MessageFormat;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/***
 *
 **/
@Slf4j
public class MusicUtil {


    static String agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36";
    private final static String api_163_songs = "http://music.163.com/api/cloudsearch/pc?s={0}&type=1&offset=1&limit=50";

    /**
     * format songId
     */
    private final static String api_163 = "http://music.163.com/api/song/enhance/player/url?ids={0}&br=320000";

    static String api_163_2 = "http://music.163.com/song/media/outer/url?id={0}.mp3";

    private static String getMusicList(String song){
        Connection.Response result  = null;
        try {
            String url = MessageFormat.format(api_163_songs, URLEncoder.encode(song,"UTF-8"));
            result = Jsoup.connect(url).userAgent( agent)
                    .header("Accept-Encoding", "gzip, deflate")
                    .method(Connection.Method.GET)
                    .maxBodySize(0)
                    /**
                     * {http://www.wityx.com/post/288_1_1.html}
                     */
                    .followRedirects(false)
                    .execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.body();
    }
    private static String getSongList(List<String> songIds){
        Connection.Response result  = null;
        try {
            String url = MessageFormat.format(api_163,songIds).replace(" ","");
            result = Jsoup.connect(url).userAgent( agent)
                    .header("Accept-Encoding", "gzip, deflate")
                    .method(Connection.Method.GET)
                    .maxBodySize(0)
                    /**
                     * {http://www.wityx.com/post/288_1_1.html}
                     */
                    .followRedirects(false)
                    .execute();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return result.body();
//        Document doc = null;
//        try {
//            String url = MessageFormat.format(api_163,songIds).replace(" ","");
//            doc = Jsoup
//                    .connect(url)
//                    .userAgent( agent)
//                    .header("Accept-Encoding", "gzip, deflate")
//                    .maxBodySize(0)
//                    .get();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        return doc.text();
    }
    public static List<MusicVo> getMusic(String song,int times){
        List<MusicVo> finalMap = Lists.newArrayList();
        try {
            //先请求163的获取歌曲接口
            String body = getMusicList(song);
            Map<String,Object> retMap = JsonUtils.toObj(body,Map.class);
            if(Objects.equals(HttpStatus.HTTP_OK,retMap.get("code"))){
                Map<String,Object> resultMap = (Map<String, Object>) retMap.get("result");

                int count = (int) resultMap.get("songCount");
                if(count>0){
                    List<Map> songs = (List<Map>) resultMap.get("songs");
                    List<String> songIds = songs.stream().map(c->c.get("id").toString()).collect(Collectors.toList());
                    //请求获取地址
                    body = getSongList(songIds);
                    Map dataMap = JsonUtils.toObj(body,Map.class);
                    if(Objects.equals(HttpStatus.HTTP_OK,dataMap.get("code"))) {
                        AtomicLong counts = new AtomicLong(0);
                        List<Map> maps = (List<Map>) dataMap.get("data");
                        maps.forEach(c->{
                            MusicVo musicVo = new MusicVo();
                            BeanUtil.fillBeanWithMap(c,musicVo,true);
                            Map map = songs.stream().filter(v->Objects.equals(v.get("id"),c.get("id"))).findFirst().get();
                            musicVo.setAuthor(((List<Map>)map.get("ar")).get(0).get("name").toString());
                            musicVo.setTitle(map.get("name").toString());
                            musicVo.setPic(((Map)map.get("al")).get("picUrl").toString());
                            musicVo.setId(songIds.get(counts.intValue()));
                            counts.incrementAndGet();
                            finalMap.add(musicVo);
                        });
                    }
                }
            }
        }catch (Exception e){
            while (times==3){
                return finalMap;
            }
            getMusic(song,++times);
        }
        return finalMap;
    }

    public static void main(String[] args) {
//        List list = Lists.newArrayList("12321313","2131231","2133454345","sadasd");
        getMusic("勿忘心安",0).forEach(System.out::println);
//        String ret = MessageFormat.format(api_163,list).replace(" ","");
//        System.out.println(ret);
    }

}
